package com.huihe.framework.handler;

import com.alibaba.fastjson2.JSON;
import com.huihe.common.entity.AjaxResult;
import com.huihe.common.utils.MessageUtils;
import com.huihe.common.utils.ServletUtils;
import com.huihe.storage.dto.LoginUser;
import com.huihe.framework.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * 用户登出处理器
 * 在LogoutFilter中被调用执行
 */
@Component
@AllArgsConstructor
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    /**
     * Token的Service
     */
    private TokenService tokenService;

    /**
     * 用户成功登出（注销）后的处理逻辑
     * @param request HTTP请求
     * @param response HTTP响应
     * @param authentication 当前用户的认证信息
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        LoginUser loginUser = tokenService.getLoginUserByToken(request);
        //该用户已登录
        if (loginUser != null) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getRedisUUID());
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }
}
